import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Created by Kate on 09.12.2014.
 */
public class FixedCapacityConnectionPool implements ConnectionPool {
    private final BlockingQueue<Object> activeConnections;
    private final Set<Object> connections;

    public FixedCapacityConnectionPool(int capacity, ConnectionSource src) {
        activeConnections = new LinkedBlockingQueue<Object>(capacity);

        for (int i = 0; i < capacity; i++) {
            activeConnections.add(src.open());
        }

        connections = new HashSet<Object>(activeConnections);
    }

    @Override
    public Object get() throws InterruptedException {
        return activeConnections.take();
    }

    @Override
    public Object tryGet() {
        return activeConnections.peek();
    }

    @Override
    public Object tryGet(long time, TimeUnit unit) throws InterruptedException {
        return activeConnections.poll(time, unit);
    }

    @Override
    public void release(Object object) {
        if (connections.contains(object)) {
            activeConnections.add(object);
        }
    }
}
